﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MediaArtAggregator.Core.Configuration;

namespace MediaArtAggregator.Core.SearchProvider {
  public class DeviantArtSearchSource : ApiBasedSearchSource{
    public override void Search ( string search, Settings settings, SearchType searchType ) {
      this.OnSearchInitialize ( EventArgs.Empty );
      try {
        string appid = "muu7abqqn9lx";
        string url = "http://backend.deviantart.com/rss.xml?dacid={2}&q={0}+{1}";
        XDocument doc = XDocument.Load ( string.Format ( url, Utilities.GetSafeSearchString ( search ), searchType.Value == null ? string.Empty : Utilities.GetSafeSearchString (searchType.Value), appid ) );
        var images = from i in doc.Root.Element("channel").Elements ( "item" )
                     select i.Element("filename").Value;

        foreach ( string file in images ) {
          if ( !string.IsNullOrEmpty ( file ) ) {
            try {
              this.Results.Add ( new Uri ( file ) );
            } catch { } 
          }
        }
      } catch { } 

      this.OnSearchComplete ( EventArgs.Empty );
    }

    public override string ToString ( ) {
      return "search.deviantart.com";
    }
  }
}
